package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 * 
 * @author zbr
 * @date 2025-02-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    private static Integer sortNo = 1;
    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 申请入住
     * @param checkInApplyDto 申请入住dto模型
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        // 1.校验老人是否已入住 ,如果以及入住，则抛出异常信息
        Elder elder = checkElderIsEnable(checkInElderDto.getIdCardNo());
        // 2.更新床位状态为已经入住
        Bed bed = updateBenStatus(checkInConfigDto.getBedId(),1);
        // 3.新增或者更新老人
        elder = updateOrInsertElder(elder, bed, checkInElderDto);
        // 4.新增签约办理
        insertContract(elder, checkInApplyDto);
        // 5.新增入住信息
        Long checkInId = insertCheckIn(elder, checkInApplyDto);
        // 6.新增入住配置
        insertCheckInConfig(checkInId, checkInConfigDto);
    }

    /**
     * 根据入住id获取入住详细信息
     * @param id 入住id
     * @return 结果
     */
    @Override
    public CheckInDetailVo getDetailById(Long id) {

        CheckIn checkIn = getById(id);
        CheckInConfigVo checkInConfigVo = getCheckInConfigByCheckInId(checkIn);
        CheckInElderVo checkInElderVo = getCheckInElderVo(checkIn);
        Contract contract = getContract(checkInElderVo.getId(),1);
        List<ElderFamilyVo> elderFamilyVoList = null;
        try {
            elderFamilyVoList = getElderFamilyVoList(checkIn.getRemark());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

    /**
     * 获取家人信息集合
     * @param remark
     * @return
     */
    private List<ElderFamilyVo> getElderFamilyVoList(String remark) throws JsonProcessingException {
        // 创建 ObjectMapper 对象用于 JSON 解析
        ObjectMapper objectMapper = new ObjectMapper();

        // 将 JSON 字符串解析为 ElderFamilyVo 对象列表
        return objectMapper.readValue(remark, new TypeReference<List<ElderFamilyVo>>() {});
    }


    /**
     * 查询生效的合同信息
     * @param elderId
     * @param status
     * @return
     */
    private Contract getContract(Long elderId, Integer status) {
        return contractMapper.selectOne(
                new LambdaQueryWrapper<Contract>()
                        .eq(Contract::getElderId, elderId)
                        .eq(Contract::getStatus, status));

    }

    /**
     * 查询老人信息
     * @param checkIn
     * @return
     */
    private CheckInElderVo getCheckInElderVo(CheckIn checkIn) {
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        int now = LocalDateTime.now().getYear();
        String birthday = elder.getBirthday();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        int start = LocalDate.parse(birthday, dateFormatter).getYear();
        checkInElderVo.setAge(now - start);
        return checkInElderVo;
    }

    /**
     * 查询入住配置
     * @param checkIn 入住信息
     * @return 结果
     */
    private CheckInConfigVo getCheckInConfigByCheckInId(CheckIn checkIn) {
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(
                new LambdaQueryWrapper<CheckInConfig>()
                        .eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        return checkInConfigVo;
    }

    /**
     * 新增入住配置
     * @param checkInId 入住信息id
     * @param checkInConfigDto 入住配置信息
     */
    private void insertCheckInConfig(Long checkInId, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(checkInId);
        checkInConfig.setSortOrder(sortNo ++);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param elder 老人
     * @param checkInApplyDto 信息
     */
    private Long insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckIn checkIn = BeanUtil.toBean(checkInConfigDto, CheckIn.class);
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setSortOrder(sortNo ++);
        if (CollUtil.isNotEmpty(elderFamilyDtoList)) {
            checkIn.setRemark(JSONUtil.toJsonStr(elderFamilyDtoList));
        }
        checkInMapper.insert(checkIn);
        return checkIn.getId();
    }

    /**
     * 新增签约办理
     * @param elder 老人
     * @param checkInApplyDto 信息
     */
    private void insertContract(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        if (ObjUtil.isNull(checkInContractDto.getAgreementPath())) {
            throw new BaseException("入住合同不能为空");
        }
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setElderId(elder.getId().intValue());
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(0);
        contract.setSortOrder(sortNo ++);
        contractMapper.insert(contract);
    }

    /**
     * 新增或者更新老人
     * @param elder 老人
     * @param bed 床位
     * @return 结果
     */
    private Elder updateOrInsertElder(Elder elder, Bed bed, CheckInElderDto checkInElderDto) {
        if (ObjUtil.isNotNull(elder)) {
            // 更新
            elder.setStatus(1);
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elderMapper.updateById(elder);
        } else {
            // 新增
            elder = BeanUtil.toBean(checkInElderDto, Elder.class);
            elder.setStatus(1);
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 更新床位状态
     * @param bedId 床位id
     * @param status 床位状态
     * @return 结果
     */
    private Bed updateBenStatus(Long bedId, int status) {
        Bed bed = bedMapper.selectById(bedId);
        bed.setBedStatus(status);
        bedMapper.updateById(bed);
        return bed;
    }

    /**
     * 校验老人是否已入住 ,如果以及入住，则抛出异常信息
     * @param idCardNo 老人身份证
     * @return 结果
     */
    private Elder checkElderIsEnable(String idCardNo) {
        Elder elder = elderMapper.selectOne(
                new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, idCardNo)
        );
        if (ObjUtil.isNotNull(elder) && elder.getStatus().equals(1)) {
            throw new BaseException("当前老人已入住");
        }
        return elder;
    }
}
